package com.oig.sys.auth.controller;


import com.oig.common.exception.BadRequestException;
import com.oig.common.module.SysResponse;
import com.oig.common.validator.GroupAdd;
import com.oig.common.validator.GroupEdit;
import com.oig.sys.auth.dto.SystemDto;
import com.oig.sys.auth.service.ITbSystemService;
import com.oig.sys.auth.vo.SystemVo;
import com.oig.sys.log.annotation.SysLog;
import com.oig.sys.security.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Tag(name = "4-子应用管理")
@RestController
@RequestMapping("/system")
@Slf4j
public class TbSystemController {

    private final ITbSystemService systemService;

    @Autowired
    public TbSystemController(ITbSystemService systemService) {
        this.systemService = systemService;
    }

    @PreAuthorize("@pms.hasPermission('/system/addSystem')")
    @SysLog(value="添加子应用",apiUrl="/system/addSystem")
    @Operation(summary = "添加子应用")
    @PostMapping("/addSystem")
    public SystemVo addSystem(@RequestBody @Validated(GroupAdd.class) SystemDto systemDto) {
        log.info("add system:{}", systemDto.toString());
        if (SecurityUtil.getDefineUserMain().getTenantId()!=0){
            throw new BadRequestException("租户无权操作");
        }
        return this.systemService.addSystem(systemDto);
    }

    @PreAuthorize("@pms.hasPermission('/system/updateSystem')")
    @SysLog(value="修改子应用",apiUrl="/system/updateSystem")
    @Operation(summary = "修改子应用")
    @PostMapping("/updateSystem")
    public SystemVo updateSystem(@RequestBody @Validated(GroupEdit.class) SystemDto systemDto) {
        log.info("update system:{}", systemDto.toString());
        if (SecurityUtil.getDefineUserMain().getTenantId()!=0){
            throw new BadRequestException("租户无权操作");
        }
        return this.systemService.updateSystem(systemDto);
    }

    @PreAuthorize("@pms.hasPermission('/system/cancelSystem')")
    @SysLog(value="逻辑删除应用",apiUrl="/system/cancelSystem")
    @Operation(summary = "逻辑删除应用")
    @PostMapping("/cancelSystem/{systemId}")
    public SysResponse<Integer> cancelSystem(@PathVariable("systemId") Integer systemId){
        log.info("cancel System systemId:{}", systemId);
        if (SecurityUtil.getDefineUserMain().getTenantId()!=0){
            throw new BadRequestException("租户无权操作");
        }
        this.systemService.cancelSystem(systemId);
        return SysResponse.ok(systemId,"成功") ;
    }


    @PreAuthorize("@pms.hasPermission('/system/revertSystem')")
    @SysLog(value="恢复应用",apiUrl="/system/revertSystem")
    @Operation(summary = "恢复应用")
    @PostMapping(value = "/revertSystem/{systemId}")
    public SysResponse<Integer> revertSystem(@PathVariable("systemId") Integer systemId){
        log.info("revert System systemId:{}",systemId);
        if (SecurityUtil.getDefineUserMain().getTenantId()!=0){
            throw new BadRequestException("租户无权操作");
        }
        this.systemService.revertSystem(systemId);
        return SysResponse.ok(systemId,"成功");
    }


    @PreAuthorize("@pms.hasPermission('/system/delSystem')")
    @SysLog(value="物理删除应用",apiUrl="/system/delSystem")
    @Operation(summary = "物理删除应用,会把应用的菜单数据、角色所拥有的权限数据全部删除")
    @PostMapping("/delSystem/{systemId}")
    public SysResponse<Integer> delSystem(@PathVariable("systemId") Integer systemId){
        log.info("del System systemId:{}", systemId);
        if (SecurityUtil.getDefineUserMain().getTenantId()!=0){
            throw new BadRequestException("租户无权操作");
        }
        this.systemService.delSystem(systemId);
        return SysResponse.ok(systemId,"成功") ;
    }


    @Operation(summary = "获取应用信息")
    @PostMapping("/info/{systemId}")
    public SystemVo info(@PathVariable("systemId") Integer systemId){
        log.info("get system info:{}",systemId);
        return this.systemService.getSystem(systemId) ;
    }


    /**
     * 登录后先进入应用列表界面
     * 如果只有一个应用，直接调用应用菜单接口，进入应用
     * 后面的业务请求，应用id和菜单id放到http头的扩展数据里
     *      X-Expand-Data:直接拼字符串 systemId;resourceId
     * @return 当前登录用户子应用权限列表
     */
    @Operation(summary = "获取用户所有子应用,可以按应用名称和应用类型查询，用户有权限的应用，如果是超级管理员所有都可以查")
    @Parameters({
            @Parameter(name = "systemName", description = "应用名称"),
            @Parameter(name = "systemTypes", description = "应用类型，多个用“,”分割")
    })
    @PostMapping("/getUserSystem")
    public List<SystemVo> getUserSystem(@RequestParam(value = "systemName", required = false) String systemName,
                                        @RequestParam(value = "systemTypes", required = false) String systemTypes){
        log.info("getUserSystem userId {}", SecurityUtil.getDefineUserMain().getId());
        return this.systemService.findSystem(systemName, systemTypes) ;
    }

}
